package com.lei.list.removeLastKthNode;

public class Node {
    public int value;
    public Node next;
    public Node(int data){
        this.value = data;
    }
    public static  Node removeLastKthNode(Node head,int k){
        if(k<1||head == null){
            return head;
        }
        //首先判断K值是否大于链表的长度
        Node cur = head;
        while(cur!=null){
            k--;
            cur = cur.next;
        }
        //接下来判断K值的三种情况
        //如果K值大于0,那肯定是K比链表长度长了，就不用管了，因为不存在倒数第K个节点值
        //当K等于0时，倒数第k个节点就是原链表的第二个节点，直接返回第二个节点就行
        if(k == 0){
            head = head.next;
        }

        if(k < 0){
            cur = head;
            //cur最终走到的位置就是要删除的节点的前一个
            while (++k != 0){
                cur = cur.next;
            }
            cur.next = cur.next.next;
        }
        return head;
    }
    public static void print(Node head){
        while (head != null){
            System.out.print(head.value + " ");
            head = head.next;
        }
    }
    public static void main(String[] args) {
        Node head1 = new Node(1);
        head1.next = new Node(3);
        head1.next.next = new Node(5);
        head1.next.next.next = new Node(6);
        System.out.print("原链表：");
        print(head1);
        System.out.println();
        System.out.print("删除后链表：");
        print(removeLastKthNode(head1,3));


    }
}
